package com.jd.fruit.model.admin.shop;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jd.fruit.common.annotation.Table;
import com.jd.fruit.common.model.BaseModel;
import com.jd.fruit.common.util.JsonConvertUtil;
import com.jd.fruit.common.util.StringUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * 商品分类
 * 
 */
@SuppressWarnings("serial")
@Table("t_category")
public class Category extends BaseModel<Category> { 
	public static final Category dao = new Category();
	
	
	/**
	 * 保存菜单
	 * @param role
	 */
	public String save(Category category){
		try {
			String key=StringUtil.getKey();
			category.set("id",key);
			category.save();
			return key;
		} catch (Exception e) {
			throw new RuntimeException("商品类型保存异常！", e);
		}
	}

	/**
	 * 读取菜单tree
	 * @param type
	 * @return
	 */
	public JSONArray loadTree(String rolemap){
		String sql="SELECT * FROM `t_category` order by sort_order";
		List<Record> recordList=Db.find(sql);
		//预留角色map，在以后所属栏目默认选中
	 
	    if(recordList.size()>0){
	    	 return JsonConvertUtil.tranformToJSON(recordList, rolemap);
		}
	    //默认数据
	    JSONArray defaultArray=new JSONArray();
		JSONObject defaultResult=new JSONObject();
		defaultResult.put("data", "no have data!");
		defaultArray.add(defaultResult);
		return defaultArray;
	}
	
	public String loadTreeGrid(){
		String sql="SELECT `id`,`cat_name`,`parent_id`,`sort_order`,`cat_desc` FROM `t_category` order by sort_order";
		List<Record> recordList=Db.find(sql);
		//预留角色map，在以后所属栏目默认选中
		if(recordList.size()>0){
	       return JsonConvertUtil.getFormatData(recordList);
		}
		 //默认数据
		JSONObject defaultResult=new JSONObject();
		defaultResult.put("data", "no have data!");
		return defaultResult.toJSONString();
	} 
	
	/**
	 * 获得父级数据
	 * @param parentid
	 * @return
	 */
	public Category getParent(String parentid){
		String sql="select * from t_category where id=?";
		return this.findFirst(sql,parentid);
	}
	
	
	
	/**
	 * 查询出所有子分类
	 * @return
	 */
	public List<Category> getChildCat(){ 
		String sql="SELECT * FROM `t_category` tc WHERE tc.id NOT IN (SELECT c.`parent_id` FROM `t_category` c WHERE c.`parent_id` IS NOT  NULL)";
		return this.find(sql);
	}
	
	
	
	@Override
	public void initWhere() {
		// TODO Auto-generated method stub
		
	}
	
	
}
